package com.ruoyi.web.controller.system;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaImgProcServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.lxzx.domain.UserCardRegister;
import com.ruoyi.lxzx.domain.WxUser;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.imgproc.WxImgProcQrCodeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
@Slf4j
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SysUserServiceImpl sysUserServiceImpl;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @GetMapping("/wxLogin")
    public AjaxResult wxLogin(String code) {
        if (StringUtils.isBlank(code)) {
            return AjaxResult.error("empty jscode");
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            WxUser su = loginService.wxLogin(session.getOpenid());
            return AjaxResult.success(su);
//        } catch (WxErrorException e) {
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    //    注册
    @PostMapping("/wxRegister")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult wxRegister(@RequestBody UserCardRegister register){
        if(register!= null && register.getOpenid() != null) {
            SysUser oldSu = sysUserServiceImpl.selectWxUserByOpenId(register.getOpenid());
            if(oldSu == null) {
                String openId = sysUserServiceImpl.wxRegister(register);
                if("名片已经存在,不能重复保存".equals(openId)){
                    return AjaxResult.error(openId);
                }
            }
            WxUser su = loginService.wxLogin(register.getOpenid());
            return AjaxResult.success(su);
        }else {
            return AjaxResult.error("获取不到对应的唯一标识");
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/wxInfo")
    public AjaxResult wxInfo(String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return AjaxResult.error("user check failed");
        }
        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return AjaxResult.success(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public AjaxResult phone(String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return AjaxResult.error("user check failed");
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return AjaxResult.success(phoneNoInfo);
    }
    /**
     * <pre>
     * 验证微信二维码
     * </pre>
     */
    @GetMapping("/wxCodeCheck")
    public AjaxResult wxCodeCheck(String imgUrl) {
        try {
            WxImgProcQrCodeResult result = wxMaService.getImgProcService().qrCode(imgUrl);
            if(result.getCodeResults().isEmpty()){
                return AjaxResult.error("请上传微信二维码");
            }else {
                return AjaxResult.success(result);
            }
        }catch (Exception e) {
            throw new ServiceException("请上传微信二维码");
        }
    }

    @GetMapping("/createQrcode")
    public AjaxResult wxCodeCreate(String id, String page, HttpServletResponse response) throws IOException {
        try {
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile()+"/upload/group";
            // 本地地址
//            String localPath = "D://hyyc/uploadPath/group";
            File file = new File(localPath);
            if(!file.exists()){
                file.mkdirs();
            }

            File result = wxMaService.getQrcodeService().createWxaCodeUnlimit("id="+id,page, localPath,false, "release", 200, true, null, false);
            String url = "/profile/upload/group/"+ result.getName();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data", url);
            return ajax;
        }catch (Exception e) {
            throw new ServiceException("生成二维码失败");
        }
    }


}